
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <input_event.h>
#include <common.h>
#include <stdlib.h>
#include <time.h>
#include <devnode.h>

static int input_dev_fd;
static time_t screen_touch_t = 0;

static void switch_page_notify_qt(unsigned char page)
{
	msgbuf_t msg = {0};
	struct qt_head_block *data;

	data = (struct qt_head_block *)&msg;;
	data->msgtype = MSG_CMD_UP;
	data->cmdtype = MSG_TYPE_PAGESWITCH;

	qt_msg_send(data, sizeof(struct qt_head_block));
}

//屏幕无操作 3分钟超时	作废了
void screen_touch_timeout_detect(void)
{
	time_t now;

	now = time(NULL);

	if(input_dev_fd <= 0) {
		input_dev_init();
		return;
	}

	if(now - screen_touch_t >= 180) {
		switch_page_notify_qt(2);
	}
}

static int get_inputdev_byname(char *name, int flags)
{
    int ret = -1;
    int fd = -1;
    char buf[256] = {0};

	int id = 0;
	char devname[128] = {0};

	while(1) {
		sprintf(devname, "/dev/input/event%d", id++);
		fd = open(devname, flags);//O_RDWR | O_NONBLOCK
		if (-1 == fd) {
			break;
		}

		ret = ioctl(fd, EVIOCGNAME(sizeof(devname)), buf);
		if (-1 == ret)
		{
			continue;
		}
		
		if(strstr(buf, name)) {
			DEBUG("found input dev %s\n", buf);
			return fd;
		}
		
		close(fd);
	}
	
	return -1;
}

static void *input_thread_handler(void *arg)
{
	struct input_event event;
	while (read(input_dev_fd, &event, sizeof(event)) == sizeof(event))
	{
		//DEBUG("get event: type = %d, code = %d, value = %d", event.type, event.code, event.value);
		screen_touch_t = time(NULL);
		if(EV_KEY == event.type && BTN_TOUCH == event.code && event.value == 1) {
			myexec("echo on > /sys/class/drm/card0-DSI-1/status", NULL, NULL);
			switch_page_notify_qt(0);
		}
	}
	return NULL;
}

//	/dev/input/event1	按键设备节点
int input_dev_init(void)
{
    pthread_t input_thread;
	
	/* 打开驱动程序 */
	input_dev_fd = get_inputdev_byname("goodix-ts", O_RDWR);
	if (input_dev_fd < 0)
	{
		input_dev_fd = get_inputdev_byname("Goodix Capacitive TouchScreen", O_RDWR);
	}

	if(input_dev_fd < 0)
	{
		return -1;
	}

	pthread_create(&input_thread, NULL, input_thread_handler, NULL);

	screen_touch_t = time(NULL);

	return 0;
}

